import React, { Component } from "react";
import styles from './index.less';
import { Modal, Button, Upload, Icon, message, Progress, notification } from 'antd';
import UserSession from "@/UserSession";
import { getFileInfo } from "@/services/knowledgeFile";
import axios from 'axios';
const { Dragger } = Upload;
const { confirm, destroyAll } = Modal;
import pptImg from '@/assets/ppt.png';
import pdfImg from '@/assets/pdf.png';
import txtImg from '@/assets/txt.png';
import fileImg from '@/assets/file.png';
import wrodImg from '@/assets/wrod.png';

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

class UploadFile extends Component {
	state = {
		initType: null, // BATCH: 批量上传; UPDATA: 更新上传;
		visible: false,
		fileList: [],
		uploading: null, // load: 上传中; done: 上传成功;
		fileIndex: null,
		complete: null,
	};

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this)
		}
	}

	componentWillUnmount() {
		destroyAll()
	}

	showModal = type => {
		this.setState({ visible: true, initType: type });
	};

	handleOk = e => {
		const { fileCategoryId, fileCategoryPath, rootCategoryId } = this.props;
		const { fileList, initType } = this.state;
		let _this = this;
		clearTimeout();
		if (fileList.length > 0) {
			this.setState({ uploading: 'load' }, () => {
				const formData = new FormData();
				formData.append('rootCategoryId', rootCategoryId);
				if (initType && initType == 'UPDATA') {
					formData.append('id', this.props.fileId);
					formData.append('opType', 1);
				} else {
					formData.append('opType', 0);
					formData.append('categoryId', fileCategoryId);
					formData.append('categoryPath', fileCategoryPath);
				};
				fileList.forEach(file => {
					formData.append('file', file.originFileObj);
				});
				const headData = {
					'Content-Type': 'application/x-www-form-urlencoded',
					Authorization: `Bearer ${UserSession.getToken()}`,
				};
				return new Promise(resolve => {
					axios.post('/cloud/doc/uploadDoc', formData, {
						headers: headData,
						cancelToken: source.token,
						onUploadProgress: (progressEvent) => {
							if (progressEvent.lengthComputable) {
								var complete = (((progressEvent.loaded / progressEvent.total) * 100) | 0);
								// 进度数
								// console.log(complete);
								_this.setState({ complete });
							}
						},
					}).then(res => {
						// console.log(res);
						if (res.data.code == 0) {
							_this.setState({ uploading: 'done' });
							setTimeout(() => {
								_this.handleCancel();
								if (_this.props.getFileList) {
									_this.props.getFileList(1)
								};
								if (_this.props.fileId) {
									_this.getFileItemInfo()
								}
							}, 1000)
						} else {
							notification['error']({
								message: res.data.message,
							})
							_this.setState({ uploading: 'error' });
							// _this.handleCancel();
						}
					});
				});
			});
		} else {
			message.error("请先选择文档，再上传！")
		}
	};

	getFileItemInfo = async () => {
		let res = await getFileInfo({ id: this.props.fileId });
		// console.log(res);
		if (this.props.updateItemFile) {
			this.props.updateItemFile(res)
		}
	};

	handleCancel = e => {
		this.setState({
			initType: null,
			visible: false,
			fileList: [],
			uploading: null,
			fileIndex: null,
		});
	};

	abortUpload = () => {
		let that = this;
		confirm({
			title: '放弃本次上传',
			content: '放弃上传会导致所有文档上传失败请谨慎操作',
			okText: '确认放弃',
			cancelText: '取消',
			maskClosable: false,
			onOk() {
				return new Promise((resolve, reject) => {
					setTimeout(() => {
						source.cancel('取消请求');
						Math.random() > 0.5 ? resolve() : reject();
						that.setState({ uploading: 'done' });
					}, 1000);
				}).catch(() => console.log('Oops errors!'));
			},
			onCancel() { },
		});
	};

	handleUpFile = (info) => {
		const { initType } = this.state;
		let fileList = [...info.fileList];
		switch (initType) {
			case 'UPDATA':
				fileList = fileList.slice(-1);
				fileList = fileList.map((file) => {
					if (file.response) {
						file.url = file.response.url;
					};
					return file;
				});
				if (
					info.file.name.indexOf('.txt') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.pdf') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.doc') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.docx') !== info.file.name.length - 5 &&
					info.file.name.indexOf('.ppt') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.pptx') !== info.file.name.length - 5
				) {
					message.error("仅支持文件格式：.txt .pdf .doc .docx .ppt .pptx");
					this.setState({ fileList: [] });
				} else {
					this.setState({ fileList });
				};
				break;

			default:
				fileList = fileList.map((file) => {
					if (file.response) {
						file.url = file.response.url;
					};
					return file;
				});
				if (
					info.file.name.indexOf('.txt') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.pdf') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.doc') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.docx') !== info.file.name.length - 5 &&
					info.file.name.indexOf('.ppt') !== info.file.name.length - 4 &&
					info.file.name.indexOf('.pptx') !== info.file.name.length - 5
				) {
					message.error("仅支持文件格式：.txt .pdf .doc .docx .ppt .pptx");
					fileList = info.fileList.filter(item => item.name != info.file.name);
					this.setState({ fileList });
				} else {
					this.setState({ fileList });
				};
				break;
		}
	};

	onMouseOver = index => {
		this.setState({ fileIndex: index })
	};

	onMouseOut = () => {
		this.setState({ fileIndex: null })
	};

	removeFile = file => {
		this.setState((state) => {
			const index = state.fileList.indexOf(file);
			const newFileList = state.fileList.slice();
			newFileList.splice(index, 1);
			return {
				fileList: newFileList,
			};
		});
	}

	render() {
		const { initType, uploading, fileList, fileIndex, complete } = this.state;
		const props = {
			name: 'file',
			multiple: true,
			showUploadList: false,
			onRemove: (file) => this.removeFile(file),
			beforeUpload: (file) => {
				this.setState((state) => ({
					fileList: [...state.fileList, file],
				}));
				return false;
			},
			accept: ".txt,.pdf,.doc,.docx,.ppt,.pptx",
			fileList,
			onChange: this.handleUpFile,
		};
		let contentText = () => {
			let contentHtml = '';
			switch (uploading) {
				case 'load':
					contentHtml = (
						<div className={styles.cardUploadPrompt}>
							<div className={styles.promptText}>
								<Icon type="exclamation-circle" theme="filled" style={{ marginRight: 6, fontSize: '17px' }} />
								<span>放弃上传会导致所有文档上传失败请谨慎操作。文档上传中，请勿刷新或关闭页面，会导致此次上传失败。</span>
							</div>
							<div className={styles.promptIcon}>
								<div>
									<Icon type="loading" style={{ marginRight: 12, color: '#3E5BFF', fontSize: '24px' }} />
									<span>{fileList.length}个文档正在上传中，请稍候…</span>
								</div>
								<Progress percent={complete ? complete : 0} showInfo={false} strokeColor="#3E5BFF" />
							</div>
						</div>
					);
					break;

				case 'done':
					contentHtml = (
						<div className={styles.cardUploadPrompt}>
							<div className={styles.promptIcon} style={{ paddingTop: 0 }}>
								<div style={{ margin: '0 0 10px' }}>
									<Icon type="check-circle" theme="filled" style={{ marginRight: 12, color: '#65B85D', fontSize: '20px' }} />
									<span>{fileList.length}个文档上传成功！</span>
								</div>
								<Progress percent={100} showInfo={false} strokeColor="#3E5BFF" />
							</div>
						</div>
					);
					break;
				case 'error':
					contentHtml = (
						<div className={styles.cardUploadPrompt}>
							<div className={styles.promptIcon} style={{ paddingTop: 0 }}>
								<div style={{ margin: '0 0 10px' }}>
									<Icon type="close-circle" theme="filled" style={{ marginRight: 12, color: 'red', fontSize: '20px' }} />
									<span>{fileList.length}个文档上传失败！</span>
								</div>
								<Progress percent={100} showInfo={false} strokeColor="red" />
							</div>
						</div>
					);
					break;

				default:
					contentHtml = (
						<Dragger {...props}>
							<p className="ant-upload-drag-icon">
								<Icon type="inbox" />
							</p>
							<p className="ant-upload-text" style={{ fontSize: '14px' }}><span style={{ color: '#3F5CFF' }}>点击</span>或将文件拖拽到这里上传</p>
							<p className="ant-upload-hint">支持扩展名：.txt .pdf .doc .docx .ppt .pptx</p>
						</Dragger>
					);
					break;
			};
			return contentHtml;
		};
		let getTitle = () => {
			let title = '';
			switch (initType) {
				case 'UPDATA':
					title = uploading ? "文件上传中" : "文档更新上传";
					break;

				default:
					title = uploading ? "文件上传中" : "文档批量上传";
					break;
			};
			return title;
		};
		// console.log(fileList);
		let getImg = (key) => {
			let imgHtml = '';
			switch (key) {
				case 'doc':
					imgHtml = <img src={wrodImg} style={{ width: '28px' }} />;
					break;
				case 'docx':
					imgHtml = <img src={wrodImg} style={{ width: '28px' }} />;
					break;

				case 'ppt':
					imgHtml = <img src={pptImg} style={{ width: '28px' }} />;
					break;
				case 'pptx':
					imgHtml = <img src={pptImg} style={{ width: '28px' }} />;
					break;

				case 'pdf':
					imgHtml = <img src={pdfImg} style={{ width: '28px' }} />;
					break;

				case 'txt':
					imgHtml = <img src={txtImg} style={{ width: '28px' }} />;
					break;

				default:
					imgHtml = <img src={fileImg} style={{ width: '28px' }} />;
					break;
			};
			return imgHtml;
		};

		return (
			<Modal
				title={getTitle()}
				visible={this.state.visible}
				onCancel={uploading === 'load' ? null : this.handleCancel}
				footer={uploading === 'load' ? [
					<Button type="primary" onClick={this.abortUpload}>放弃本次上传</Button>,
				] : uploading === 'done' ? [
					<Button type="primary" onClick={this.handleCancel}>关闭</Button>,
				] : [
					<Button onClick={this.handleCancel}>取消</Button>,
					<Button type="primary" onClick={this.handleOk}>上传文档</Button>,
				]}
				className={styles.modalCard}
				closable={uploading !== 'load'}
				destroyOnClose
				width={750}
			>
				{contentText()}
				<div className={styles.fileListCard}>
					{fileList.map((file, index) => {
						return (
							<div key={index + 1} style={{ margin: '10px 0 0' }}>
								<div className={styles.fileCard} onMouseOver={() => this.onMouseOver(index + 1)} onMouseOut={this.onMouseOut}>
									<div style={{ display: 'flex', alignItems: 'center' }}>
										<span style={{ marginRight: 10 }}>
											{/* <img src={pdfImg} style={{ width: '28px' }} /> */}
											{getImg(file.name?.split('.')?.length > 1 ? file.name.split('.')[1] : null)}
										</span>
										<span>
											<span style={{ color: '#000' }}>{file.name}</span>
											<br />
											<span style={{ color: '#999', fontSize: '12px' }}>{Math.round(file.size / 1024)}KB</span>
										</span>
									</div>
									{uploading ? null : fileIndex && index + 1 === fileIndex ? (
										<Icon type="delete" onClick={() => this.removeFile(file)} />
									) : (
										<Icon type="check-circle" theme="filled" style={{ color: '#65B85D' }} />
									)}
								</div>
							</div>
						)
					})}
				</div>
			</Modal>
		);
	}
}

export default UploadFile;
